class Scratch {
  constructor(page, opts) {
    opts = opts || {};
    this.page = page;
    this.canvasId = opts.canvasId || 'canvas';
    this.width = opts.width || 300;
    this.height = opts.height || 300;
    this.maskColor = opts.maskColor || '#dddddd';
    this.size = opts.size || 15,
      //this.r = this.size * 2;
    this.r = this.size;
    this.area = this.r * this.r;
    //this.scale = opts.scale || 0.7;
    this.scale = opts.scale || .5;
    this.totalArea = this.width * this.height;
    this.init();
    this.api = false; // 是否已经请求过抽奖接口 false：没有 true： 请求了
    this.move = false; // 是否已经移动 false
    this.verify = false; // 是否已经调用验证接口 false：没有 true： 请求了
    this.timer = null; // 是否已经调用验证接口 false：没有 true： 请求了
   
  }
  init() {
    this.show = false;
    this.clearPoints = [];
    this.button = {x:0, y:0, w:0, h: 0} // 按钮的坐标点
    this.ctx = wx.createCanvasContext(this.canvasId, this);
    this.drawMask();
    this.bindTouch();
    // this.drawErr()
    // this.drawPrize()
  }
  drawMask() {
    // this.ctx.setFillStyle(this.maskColor);
    // this.ctx.fillRect(0, 0, this.width, this.height);
    // this.ctx.draw();.
    let str = "刮奖区"
    const { canvasWidth, canvasHeight, imageResource, maskColor } = this
    const self = this
    this.ctx = wx.createCanvasContext('canvasLock')
    this.ctx.drawImage('/images/scratch_off.png', 0, 0, this.width, this.height  )
    this.ctx.setFontSize(36* this.page.data.ratio)
    this.ctx.setFillStyle("#999999")
    this.ctx.fillText(str, (this.width - this.ctx.measureText(str).width) / 2, 100 * this.page.data.ratio, this.width, this.height);
    this.ctx.draw(true)


    // console.log('绘制完成')
  }
  // 没有奖品
  drawNoPrize(str, text="再接再厉" ) {
    const ratio = this.page.data.ratio
    this.ctx = wx.createCanvasContext('canvasLock')
    // this.ctx.drawImage('/images/scratch_off.png', 0, 0, this.width, this.height)
    this.ctx.setFontSize(22 * ratio)
    this.ctx.setFillStyle("#000")
    this.ctx.fillText(str, (this.width - this.ctx.measureText(str).width) / 2, 60 * ratio, this.width, this.height)

    this.ctx.setStrokeStyle('red')
    this.ctx.moveTo(10, 10)
    this.ctx.rect((this.width - 225 * ratio) / 2, 112 * ratio, 225 * ratio, 40 * ratio)
    this.button = {
      x:(this.width - 225 * ratio) / 2,
      y: 112 * ratio,
      w: 225 * ratio,
      h: 40 * ratio
    }
    this.ctx.setFontSize(17 * ratio)
    this.ctx.setFillStyle("#F23348")
    this.ctx.font = `normal bold ${17 * ratio} sans-serif`;
    this.ctx.fillText(text, (this.width - this.ctx.measureText(text).width) / 2, 140 * ratio, this.width, this.height)
    this.ctx.stroke()
    this.ctx.draw(true)
  }
  // 中奖绘制奖品
  drawPrize(str, giftName,   text = "再玩一次") {
    const ratio = this.page.data.ratio
    this.ctx = wx.createCanvasContext('canvasLock')
    // this.ctx.drawImage('/images/scratch_off.png', 0, 0, this.width, this.height)
    this.ctx.setFontSize(20 * ratio)
    this.ctx.setFillStyle("#000")
    let row = this.textRow(this.ctx, str, this.width - 20 * ratio)
    for (var b = 0; b < row.length; b++) {
      this.ctx.fillText(row[b], (this.width - this.ctx.measureText(row[b]).width) / 2, (30 * ratio) + b * (20 * ratio), this.width, this.height);
    }
    // this.ctx.fillText(str, (this.width - this.ctx.measureText(str).width) / 2, 40 * ratio, this.width, this.height)


    this.ctx.setFontSize(25* ratio)
    // this.ctx.font = `bold ${25 * ratio} sans-serif`;
    this.ctx.setFillStyle("#EB1212")
    let giftNamerow = this.textRow(this.ctx, giftName, this.width - 25 * ratio)
    for (var b = 0; b < giftNamerow.length; b++) {
      this.ctx.fillText(giftNamerow[b], (this.width - this.ctx.measureText(giftNamerow[b]).width) / 2, (80 * ratio) + b * (25 * ratio), this.width, this.height);
    }

    const grd = this.ctx.createLinearGradient(0, 225 * ratio, 40 * ratio, 0)
    grd.addColorStop(0, '#FE9552')
    grd.addColorStop(1, '#D9383D')
    this.ctx.setFillStyle(grd)
    // this.ctx.moveTo(10, 10)
    this.ctx.fillRect((this.width - 225 * ratio) / 2, 112 * ratio, 225 * ratio, 40 * ratio)



    this.button = {
      x:(this.width - 225 * ratio) / 2,
      y: 112 * ratio,
      w: 225 * ratio,
      h: 40 * ratio
    }
    console.log(this.button)
    this.ctx.setFontSize(17 * ratio)
    this.ctx.setFillStyle("#fff")
    // this.ctx.font = `normal bold ${17 * ratio} sans-serif`;
    this.ctx.fillText(text, (this.width - this.ctx.measureText(text).width) / 2, 140 * ratio, this.width, this.height)
    this.ctx.stroke()
    this.ctx.draw(true)
  }
  drawErr(str) {
    const ratio = this.page.data.ratio
    this.ctx = wx.createCanvasContext('canvasLock')
    // this.ctx.drawImage('/images/scratch_off.png', 0, 0, this.width, this.height)
    this.ctx.setFontSize(22 * this.page.data.ratio)
    this.ctx.setFillStyle("#999999")
    let row = this.textRow(this.ctx, str, this.width - 20 * ratio)
    for (var b = 0; b < row.length; b++) {
      this.ctx.fillText(row[b], (this.width - this.ctx.measureText(row[b]).width) / 2, (100 * ratio) + b * (22 * ratio), this.width, this.height);
    }
    // this.ctx.fillText(str, (this.width - this.ctx.measureText(str).width) / 2, 100 * this.page.data.ratio, this.width, this.height);
    this.page.setData({
      canvasClear: true
    })
    this.ctx.draw(true)

    // this.ctx.draw(true)
  }
  bindTouch() {
    this.page.touchStart = (e) => {
      console.log(this.page)
      // 事件坐标
      const position = e.touches[0]
      console.log(position)
      console.log(this.button)
      if(position.x > this.button.x && position.x < this.button.x + this.button.w ) {
        if (position.y > this.button.y && position.y < this.button.y + this.button.h) {
          console.log('在按钮上')
          this.page.handleAgain()
        }
        // console.log('在x轴上')
      }
      // this.eraser(e, true);
      // 开始判断是登录和是否有会员ID
      this.page.isLogin();
      this.page.isMemberId();
    }
    this.page.touchMove = (e) => {
      console.log('移动')
      // // 如果没有会员ID不做操作
      if (!this.page.data.memberId) {
        return null
      }
      // 没有详情提示
      if(!this.page.data.detailData) {
        console.log('没有详情')

        wx.showToast({
          title: "暂无此类型活动",
          icon: 'none',
          duration: 2000
        })
       return null;
      }
      if (this.page.data.detailData.activityStatus == 0) {
        wx.showToast({
          title: `${'游戏未开始'}`,
          icon: 'none',
          duration: 2000
        })
        return null
      } else if (this.page.data.detailData.activityStatus == 2) {
        wx.showToast({
          title: `${'游戏已结束'}`,
          icon: 'none',
          duration: 2000
        })
        return null
      }
      // if (!this.page.data.canvasFlang) { // 接口验证是否通过
      // } else {
        if (!this.timer) {
          setTimeout(()=> {
            this.timer = true
          }, 100)
          
        } else {
          this.eraser(e, false);
        }
        
      // }
 
      // if (this.page.data.getGameLottery)
      // this.eraser(e, false);

    }
    this.page.touchEnd = (e) => {
      // if (this.show) {
      //   this.page.clearCanvas();
      //   this.ctx.clearRect(0, 0, this.width, this.height);
      //   this.ctx.draw();
      // }
    }
  }
  eraser(e, bool) {
    if (this.page.data.canvasClear) return null
    let len = this.clearPoints.length;
    let count = 0;
    let x = e.touches[0].x,
      y = e.touches[0].y;
    let x1 = x - this.size;
    let y1 = y - this.size;
    if (bool) {
      this.clearPoints.push({
        x1: x1,
        y1: y1,
        x2: x1 + this.r,
        y2: y1 + this.r
      })
    }
    for (let item of this.clearPoints) {
      if (item.x1 > x || item.y1 > y || item.x2 < x || item.y2 < y) {
        count++;
      } else {
        break;
      }
    }
    if (len === count) {
      this.clearPoints.push({
        x1: x1,
        y1: y1,
        x2: x1 + this.r,
        y2: y1 + this.r
      });
    }
    // console.log(this.clearPoints)
    //添加计算已清除的面积，达到标准值后，设置刮卡区域刮干净
    let clearNum = parseFloat(this.r * this.r * len) / parseFloat(this.scale * this.totalArea);
    if (!this.show) {
      this.page.setData({
        clearNum: parseFloat(this.r * this.r * len) / parseFloat(this.scale * this.totalArea)
      })
    }
    if (clearNum > .2) {
      console.log('清除完毕')
      // this.page.canvasTouch()
      // this.api = false; // 是否已经请求过抽奖接口 false：没有 true： 已经清楚
      if(!this.api) {
        this.api = true
        this.page.canvasTouch()
      }
      //if (len && this.r * this.r * len > this.scale * this.totalArea) {
      // this.show = true;
    }
    this.clearArcFun(x, y, this.r, this.ctx);
    this.ctx.draw(true);
  }
  clearArcFun(x, y, r, ctx) {
    let stepClear = 1;
    clearArc(x, y, r);

    function clearArc(x, y, radius) {
      let calcWidth = radius - stepClear;
      let calcHeight = Math.sqrt(radius * radius - calcWidth * calcWidth);

      let posX = x - calcWidth;
      let posY = y - calcHeight;

      let widthX = 2 * calcWidth;
      let heightY = 2 * calcHeight;

      if (stepClear <= radius) {
        ctx.clearRect(posX, posY, widthX, heightY);
        stepClear += 1;
        clearArc(x, y, radius);
      }
    }
  }
  textRow(context, text, width ){
    var chr = text.split("");//这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < width) {
        temp += chr[a];
      }
      else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < width) {
          test += rowPart[a];
        }
        else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..."//这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    return row
    // for (var b = 0; b < row.length; b++) {
    //   context.fillText(row[b], 10, 30 + b * 30, 300);
    // }
    // context.draw()    
  }
}

export default Scratch